package club.dmyang.controller;

import club.dmyang.common.vo.ResposeVo;
import club.dmyang.entity.Tag;
import club.dmyang.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by brss on 2018/7/15.
 */
@Controller
@RequestMapping("/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    /**
     * 分页列出所有标签
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResposeVo list(Integer page,Integer limit){
        List<Tag> tagList = tagService.findByPageAndLimit(page, limit);
        //获取所有标签的个数
        int count = tagService.findAllNums();
        return new ResposeVo(0,"成功",count,tagList);
    }

    /**
     * 跳转到编辑页面（填充响应表单）
     * @param tid
     * @param model
     * @return
     */
    @RequestMapping("/edit/{tid}")
    public String edit(@PathVariable("tid") Integer tid, Model model){
        Tag tag = tagService.findOneById(tid);
        model.addAttribute("tag",tag);
        return "admin/tag-add";
    }

    /**
     * 更新一个标签
     * @param tag
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(Tag tag){
        boolean b = tagService.updateOneTag(tag);
        if (b)
            return "更新标签成功";
        else
            return "更新标签失败";
    }

    /**
     * 删除一个标签
     * @param tid
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete/{tid}")
    public String delete(@PathVariable("tid") Integer tid){
        boolean b = tagService.deleteOneTag(tid);
        if (b)
            return "删除标签成功";
        else
            return "删除标签失败";
    }

    @ResponseBody
    @RequestMapping("/add")
    public String add(Tag tag){
        boolean b = tagService.addOneTag(tag);
        if (b)
            return "添加标签成功";
        else
            return "添加标签失败";
    }
}
